<template>
  <div>
    <a-card>
      <a-form layout="horizontal">
        <div>
          <a-row >
            <a-col :md="6" :sm="24" >
              <a-form-item label="选择园区" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                <a-select v-model="query.farmId" placeholder="请选择园区" @change="farmChange">
                  <a-select-option
                      v-for="(item, index) in farmList"
                      :key="index" :value="item.FarmId">
                    {{item.FarmName}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" >
              <a-form-item label="选择地块" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                <a-select v-model="query.greenHouseId" placeholder="请选择地块">
                  <a-select-option
                      v-for="(item, index) in greenHouseList"
                      :key="index" :value="item.GreenHouseId">
                    {{item.GreenHouseName}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <div style="margin: 3px 0 0 8px;">
                <a-button type="primary" @click="search">查询</a-button>
              </div>
            </a-col>
          </a-row>
        </div>
      </a-form>
      <a-space class="operator">
        <a-button @click="goPage" type="primary">新建</a-button>
      </a-space>
    </a-card>
    <a-card title="溯源详情" style="margin-top: 10px" v-if="loading">
      <a-row>
        <a-col :md="16" :sm="24">
          <a-form-model
              ref="traceIndexForm"
              :model="data"
              :rules="rules"
              :label-col="{span: 4}"
              :wrapper-col="{span: 14}">
            <a-form-model-item label="溯源码" prop="queryCode">
              <a-input v-model="data.queryCode" type="text" disabled/>
            </a-form-model-item>
            <a-form-model-item label="页面标题" prop="company">
              <a-input v-model="data.company" default-value="YesIoT 智慧农业溯源系统" type="text" allowClear/>
            </a-form-model-item>
            <a-form-model-item label="地块类型" prop="houseType">
              <a-input v-model="data.houseType" type="text" allowClear/>
            </a-form-model-item>
            <a-form-model-item label="作物名称" prop="plantName">
              <a-input v-model="data.plantName" type="text" allowClear/>
            </a-form-model-item>
            <a-form-model-item label="种植日期" prop="plantDate">
              <a-date-picker
                  v-model="data.plantDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 200px;"
                  @change="(m, v) => dateChange(v,'plant')"
              />
            </a-form-model-item>
            <a-form-model-item label="种植面积" prop="size">
              <a-input v-model="data.size" type="text" allowClear/>
            </a-form-model-item>
            <!-- NEW FIELD-->
            <a-form-model-item label="土壤质量" prop="earth">
              <a-input v-model="data.earth" type="text" allowClear/>
            </a-form-model-item>
            <a-form-model-item label="种植状态" prop="plantStatus">
              <a-input v-model="data.plantStatus" type="text" allowClear/>
            </a-form-model-item>
            <a-form-model-item label="质量检测" prop="quality">
              <a-input v-model="data.quality" type="text" allowClear/>
            </a-form-model-item>
            <a-form-model-item label="最后检测日期" prop="lastCheck">
              <a-date-picker
                  v-model="data.lastCheck"
                  type="date"
                  placeholder="选择日期"
                  style="width: 200px;"
                  @change="(m, v) => dateChange(m, v,'check')"
              />
            </a-form-model-item>
            <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
              <a-button type="primary" @click="sub">
                提交
              </a-button>
              <a-button style="margin-left: 10px;" @click="reset">
                重置
              </a-button>
            </a-form-model-item>
          </a-form-model>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-card size="small" title="溯源二维码">
            <div class="qrcode-main">
              <div id="qrcode" ref="qrcode" class="qrcode"></div>
              <div class="qrcode-url" >
                <p>
                  <a :href="qrcodeUri(data.queryCode)" target="_blank">{{qrcodeUri(data.queryCode)}}</a>
                </p>
              </div>
            </div>
          </a-card>
          <div class="admin-list">
            <a-table :columns="columns" :data-source="owners"
                     :rowKey="(data, index) => index"
                     :pagination="false" bordered>
              <template slot="title">
                管理员信息
              </template>
              <template slot="footer">
                <div class="admin-add">
                  <div class="add-name">选择管理员</div>
                  <div class="add-list">
                    <a-select placeholder="请选择管理员" style="width: 200px" label-in-value @change="selectManager" allowClear>
                      <a-select-option
                          v-for="(item, index) in managerList"
                          :key="index" :value="index">
                        {{fullManager(item)}}
                      </a-select-option>
                    </a-select>
                  </div>
                  <div class="add-btn" @click="addManager"><a-icon type="plus" /> 添加</div>
                </div>
              </template>
               <span slot="action" slot-scope="text, record">
                   <a-popconfirm title="确定删除?" @confirm="delRecord(record)">
                    <a-icon slot="icon" type="question-circle-o" style="color: red" />
                    <a href="#" style="color: #f5222d"><a-icon type="delete" />删除</a>
                  </a-popconfirm>
               </span>
            </a-table>
          </div>
        </a-col>
      </a-row>
    </a-card>
  </div>
</template>

<script>
  import QRCode from 'qrcodejs2'
  import StandardTable from '@/components/table/StandardTable'
  import { FormModel } from 'ant-design-vue';
  import {list as farmList} from '@/services/farm'
  import { list as greenHouseList } from '@/services/greenhouse'
  import { list as managerList} from '@/services/manager'
  import {info, edit} from '@/services/trace'
  import {convertJsonKey} from '@/utils/util'
  import {qrcodeBaseUrl} from '@/config/default/setting.config'
  const columns = [
    {
      title: '昵称',
      dataIndex: 'owner',
      width: '30%',
      scopedSlots: { customRender: 'owner' },
    },
    {
      title: '手机号码',
      dataIndex: 'ownerPhone',
      width: '50%',
      scopedSlots: { customRender: 'ownerPhone' },
    },{
      title: '操作',
      dataIndex: 'action',
      scopedSlots: { customRender: 'action' },
    }
  ];
  export default {
    name: "TraceIndex",
    data() {
      return {
        QRCode: null,
        codeCache: '',
        owners: [],
        ownersCache: [],
        loading: false,
        columns,
        farmList: [],
        greenHouseList: [],
        managerList: [],
        query: {
          farmId: undefined,
          greenHouseId: undefined
        },
        data: {
          lastCheck: '',//最后检测日期
          earth: '', //土壤质量
          plantStatus: '', //种植状态
          quality: '', //质量检测
          houseType: '',
          queryCode: '',
          plantName: '',
          plantDate: '',
          size: ''
        },
        rules: {
          company: [
            { required: true, message: '请输入页面标题', trigger: 'blur' }
          ],
          plantDate: [
            { required: true, message: '请选择种植日期', trigger: 'change' }
          ],
          plantName: [
            { required: true, message: '请输入作物名称', trigger: 'blur' }
          ],
          size: [
            { required: true, message: '请输入种植面积', trigger: 'blur' }
          ]
        }
      }
    },
    computed: {
      fullManager(obj) {
        let name = ''
        return obj => {
          if(obj.AdminName) {
            name =  `${obj.Phone},${obj.AdminName}`
          } else name = obj.Phone
          return name
        }
      },
      qrcodeUri(code) {
        return code => {
          return `${qrcodeBaseUrl}?code=${code}`
        }
      }
    },
    components: {
      StandardTable,
      FormModel
    },
    created() {
      this.getFarmList()
    },
    methods: {
      async getFarmList() {
        let res = await farmList()
        this.farmList = res.Data
      },
      async getManagerList() {
        let res = await managerList(this.query.farmId)
        this.managerList = res.Data
      },
      async getGreenHouseList() {
        let res = await greenHouseList(this.query.farmId)
        this.greenHouseList = res.Data
      },
      sub() {
        this.$refs.traceIndexForm.validate(valid => {
          if (valid) {
            if(this.owners.length == 0) {
              this.$message.warning('请添加管理员')
              return
            }
            this.data.owners = this.owners
            console.log(this.data);
            edit(this.data).then(res => {
              if(res.Code == 0) {
                this.$message.success('编辑成功')
                this.search()
              } else this.$message.error('编辑失败')
            }).catch(err => {
              console.log(err)
              this.$message.error('编辑失败')
            })
          }
        })
      },
      search() {
        info(this.query.greenHouseId).then(res => {
          if(res.Code == 0) {
            this.data = convertJsonKey(res.Data)
            this.owners = this.data.owners.map(item => {
              return {
                // 转小写
                owner: item.Owner,
                ownerPhone: item.OwnerPhone
              }
            })
            this.loading = true
            this.getManagerList()
            // 生成二维码
            this.qrcode()
          } else {
            this.$message.warning('溯源信息不存在')
            Object.assign(this.$data, this.$options.data())
            this.getFarmList()
          }
        }).catch(err => {
          console.log(err);
          Object.assign(this.$data, this.$options.data())
          this.getFarmList()
          this.$message.error('请求失败')
        })
      },
      add() {

      },
      delRecord(row, index) {
        if(!row.ownerPhone) {
          this.$message.error('无效管理员')
          return
        }
        console.log(index);
        this.owners.splice(index, 1)
      },
      farmChange() {
        this.query.greenHouseId = ''
        this.getGreenHouseList()
      },
      dateChange(m, v, type) {
        switch (type) {
          case 'check':
            this.data.lastCheck = v
            break
          case 'plant':
            this.data.plantDate = v
            break
        }
      },
      selectManager(obj) {
        const labelArr = obj.label.split(',')
        this.ownersCache.ownerPhone = labelArr[0]
        this.ownersCache.owner = labelArr.length == 2 ? labelArr[1] : '' //带昵称
      },
      addManager() {
        const ownerInfo = {...this.ownersCache} //深度复制
        if(!ownerInfo.ownerPhone) {
          this.$message.error('未选择')
          return
        }
        const index = this.owners.findIndex(item => item.ownerPhone == ownerInfo.ownerPhone)
        if(index == -1) {
          this.owners.push(ownerInfo)
        } else this.$message.warning('此管理员已存在')
      },
      reset() {
        this.codeCache = this.data.queryCode
        this.$data.data = this.$options.data().data
        this.data.queryCode = this.codeCache
      },
      goPage() {
        this.$router.push({
          path: '/trace/add',
          params: {}
        })
      },
      qrcode() {
        this.$nextTick(() => {
          document.getElementById("qrcode").innerHTML = "" //清除
          this.QRCode = new QRCode('qrcode', {
            width: 180,
            height: 180,
            text: `${qrcodeBaseUrl}?code=${this.data.queryCode}`, // 二维码地址
            colorDark : "#000",
            colorLight : "#fff",
          })
        })
      },
    }
  }
</script>

<style lang="less" scoped>
  .admin-add {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .add-btn {
      color: rgb(0, 205, 0);
    }
    .add-list {
      flex: 1;
      margin:0 20px;
    }
  }
  .qrcode-main {
    height: 180px;
    display: flex;
    justify-content: flex-start;
    .qrcode {
      width: 180px;
      height: 180px;
    }
    .qrcode-url {
      margin-left: 10px;
      flex: 1;
    }
  }
</style>
